package 力扣;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 输入：root = [1,null,2,3]
 输出：[1,2,3]
 示例 2：

 输入：root = []
 输出：[]
 示例 3：

 输入：root = [1]
 输出：[1]
 */
public class _144二叉树的前序遍历 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||(!stack.empty())){
            if(root!=null){
                list.add(root.val);//步骤一，取根节点的值
                stack.push(root);
                root=root.left;//步骤二，遍历左子树
            }
            else{
                TreeNode tem=stack.pop();
                root=tem.right;//步骤三，遍历右子树
            }
        }
        return list;
    }


}
